package com.masterclient.app;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.StrictMode;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.huawei.HuaWeiRegister;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.MeizuRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.OppoRegister;
import com.alibaba.sdk.android.push.register.VivoRegister;
import com.eoner.baselib.application.BaseApplication;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.observe.ForeAndbackObserve;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.common.BuildConfig;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.netsign.NetEnvManager;
import com.eoner.managerlibrary.servertimer.ServerTimerManager;
import com.eoner.managerlibrary.sobot.SobotManager;
import com.eoner.managerlibrary.user.UserDataManager;
import com.masterclient.app.widget.imagepick.PicassoImageLoader;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.view.CropImageView;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

import io.reactivex.functions.Consumer;
import io.reactivex.plugins.RxJavaPlugins;
import okhttp3.OkHttpClient;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;

/**
 * 作者：sean
 * 创建时间：2017/6/8 14:11
 * 功能说明：
 */

public class App extends BaseApplication {

    @Override
    public void onCreate() {
        super.onCreate();
        closeAndroidPDialog();

        init();
        initCloudChannel(this);
    }

    private void init() {
        //ARouter 初始化 这两行必须写在init之前，否则这些配置在init过程中将无效
        if (BuildConfig.DEBUG) {
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(this);
        PushServiceFactory.init(this);
        initNativeMethod();
        //TODO:bugly配置
        if (BuildConfig.DEBUG) {
            CrashReport.initCrashReport(getApplicationContext(), "be860db2e5", true);
        } else {
            CrashReport.initCrashReport(getApplicationContext(), "be860db2e5", false);
        }
        CrashReport.setAppVersion(getApplicationContext(), Utils.getVersionName());

        MobclickAgent.setScenarioType(getApplicationContext(), MobclickAgent.EScenarioType.E_UM_NORMAL);

        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setMultiMode(false);
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(9);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素;

        //智齿客服的初始化
        SobotManager.initSobot(getApplicationContext(), getContentResolver());
        //友盟--------------------------------------------------------------------
        String appkey = "608522b19e4e8b6f618160e2";
        UMConfigure.init(this, appkey, "Umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newBuilder().connectTimeout(5, TimeUnit.SECONDS).readTimeout(7, TimeUnit.SECONDS).writeTimeout(7, TimeUnit.SECONDS);


        //设置rxjava 无法解析异常
        setRxJavaErrorHandler();


        if (inMainProcess(this)) {
            //TODO:业务接口环境
            NetEnvManager.configNetServiceEnv();
            //TODO:自动登陆
            UserDataManager.getInstance().autoSystemLogin();
            //TODO:首次获取服务端时间
            ServerTimerManager.getInstance().requestServerTime();
        }
    }

    private void initNativeMethod() {
        Utils.init(this);
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                .setDefaultFontPath("fonts/din.ttf")
                .setFontAttrId(R.attr.fontPath)
                .build());
        ZXingLibrary.initDisplayOpinion(this);
        ToastUtil.init(this);
        //TODO:前后台监听初始化
        ForeAndbackObserve.init(this);
        Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this));
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }


    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        if (resources != null && resources.getConfiguration().fontScale != 1.0f) {
            android.content.res.Configuration configuration = resources.getConfiguration();
            configuration.fontScale = 1.0f;
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        }
        return resources;
    }


    private void setRxJavaErrorHandler() {
        RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                throwable.printStackTrace();
            }
        });
    }

    private void initCloudChannel(final Context applicationContext) {
        // 创建notificaiton channel
        this.createNotificationChannel();
        final CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.setLogLevel(CloudPushService.LOG_DEBUG);//ogLevel 支持设置：CloudPushService.ERROR | CloudPushService.INFO | CloudPushService.DEBUG | CloudPushService.OFF（关闭Log）
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Config.DEVICE_ID = pushService.getDeviceId();
                Log.i("=======", "init cloudchannel success" + response + "=====" + pushService.getDeviceId());
//                setConsoleText("init cloudchannel success");
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Log.e("=======", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
//                setConsoleText("init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });

        MiPushRegister.register(applicationContext, "2882303761519950137", "5731995042137"); // 初始化小米辅助推送
        HuaWeiRegister.register(this); // 接入华为辅助推送
        VivoRegister.register(applicationContext);
        OppoRegister.register(applicationContext, "30df0da9fb0e4635b047610386507dd1", "9384ada8481a4e49a43d7e4f1eb397d5");
        MeizuRegister.register(applicationContext, "141309", "d00c5f4344ea49b582bacbb7a7e453ba");
    }


    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // 通知渠道的id
            String id = "1";
            // 用户可以看到的通知渠道的名字.
            CharSequence name = "notification_channel";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(id, name, importance);
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            //最后在notificationmanager中创建该通知渠道
            mNotificationManager.createNotificationChannel(mChannel);
        }
    }


    //android p 调用反射等的弹窗 app初始化的时候调用此方法就不会出现了 如果有测试或者用户提出来 调用这个方法即可
    private void closeAndroidPDialog() {
        try {
            Class aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
            declaredConstructor.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Class cls = Class.forName("android.app.ActivityThread");
            Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
            declaredMethod.setAccessible(true);
            Object activityThread = declaredMethod.invoke(null);
            Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
